#include <stdio.h>
#include <string.h>


/*
Input: Path, Application Name
Output: 1 if allowed, 0 if not allowed
*/

int check_file(char *path, char *appname)
{
	char filename[100];
	char buf[256];
	FILE *list;
	char *test;
	int i;


	char *targetName = path;
	char aName[256];

	//Create Filename
	//strncpy(filename, appname, 95);
	strcpy(filename, appname);
	strcat(filename, ".list");

	//Open File
	list = fopen(filename,"r");

	i = fscanf(list, "%s", &buf);
	while(i != EOF)
	{
		//printf("%s", buf);
		//printf("strcmp: %d\n", strcmp(path, buf));

		if (strcmp(path, buf) == 0)
		{
			printf("%s and %s are equal!\n", path, buf);
			return 1;
		}
		i = fscanf(list, "%s", &buf);
	}

	//printf("FAIL\n");
	return 0;
}

/*
Input: Directory Path, Application Name
*/
int file_creation(char *path, char *appname)
{
	return check_file(path, appname);
}

/*
Input: File Path, Application Name
*/
int file_rename(char *input, char *appname)
{
	char *delim = "/";
	char *split;
	char *prev;
	char path[256];

	split = strtok(input, delim);
	strcpy(path,"/");
	strcat(path, split);
	//printf("path: %s\n", path);
	split = strtok(NULL, delim);
	prev = strdup(split);
	split = strtok(NULL, delim);
	while(split != NULL)
	{
		strcat(path,"/");
		strcat(path, prev);
		//printf("split: %s\n", path);
		prev = strdup(split);
		split = strtok(NULL, delim);
	}

	return check_file(path, appname);
}

/*
Input: File Path, Application Name
*/
int file_overwrite(char *input, char *appname)
{
	char *delim = "/";
	char *split;
	char *prev;
	char path[256];

	split = strtok(input, delim);
	strcpy(path,"/");
	strcat(path, split);
	//printf("path: %s\n", path);
	split = strtok(NULL, delim);
	prev = strdup(split);
	split = strtok(NULL, delim);
	while(split != NULL)
	{
		strcat(path,"/");
		strcat(path, prev);
		//printf("split: %s\n", path);
		prev = strdup(split);
		split = strtok(NULL, delim);
	}

	return check_file(path, appname);
}

main(int argc, char *argv[])
{
	char input[30] = "/etc/var/www";
	char appname[10] = "Apache";
	int x;

	x = file_creation(input, appname);
	if (x == 1)
	{
		printf("SUCCESS\n");
	} else {
		printf("FAIL\n");
	}

}
